package com.example.myapplicationktkt2.okhttp

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplicationktkt2.R
import com.example.myapplicationktkt2.network.OkHttpUtil
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException

/**
 * OkHttp网络请求演示Activity
 * 演示了使用OkHttp发送GET和POST请求
 *
 * https://v.api.aa1.cn/api/zhihu-news/index.php?aa1=xiarou
 */
class OkHttpDemoActivity : AppCompatActivity() {

    // UI组件
    private lateinit var etGetUrl: EditText
    private lateinit var btnGetRequest: Button
    private lateinit var etPostUrl: EditText
    private lateinit var etPostData: EditText
    private lateinit var btnPostRequest: Button
    private lateinit var tvResult: TextView
    private lateinit var btnClear: Button

    // OkHttp工具类实例
    private val okHttpUtil = OkHttpUtil.Companion.getInstance()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_okhttp_demo)

        // 初始化UI组件
        initViews()

        // 设置点击事件
        setClickListeners()
    }

    /**
     * 初始化UI组件
     */
    private fun initViews() {
        etGetUrl = findViewById(R.id.etGetUrl)
        btnGetRequest = findViewById(R.id.btnGetRequest)
        etPostUrl = findViewById(R.id.etPostUrl)
        etPostData = findViewById(R.id.etPostData)
        btnPostRequest = findViewById(R.id.btnPostRequest)
        tvResult = findViewById(R.id.tvResult)
        btnClear = findViewById(R.id.btnClear)
    }

    /**
     * 设置点击事件监听器
     */
    private fun setClickListeners() {
        // GET请求按钮点击事件
        btnGetRequest.setOnClickListener {
            sendGetRequest()
        }

        // POST请求按钮点击事件
        btnPostRequest.setOnClickListener {
            sendPostRequest()
        }

        // 清空结果按钮点击事件
        btnClear.setOnClickListener {
            tvResult.text = ""
        }
    }

    /**
     * 发送GET请求
     */
    private fun sendGetRequest() {
        val url = etGetUrl.text.toString().trim()

        // 检查URL是否为空
        if (url.isEmpty()) {
            Toast.makeText(this, "请输入请求URL", Toast.LENGTH_SHORT).show()
            return
        }

        // 显示正在请求的提示
        tvResult.text = "正在发送GET请求...\nURL: $url"

        // 发送GET请求
        okHttpUtil.get(url, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                // 在主线程更新UI
                runOnUiThread {
                    tvResult.text = "GET请求失败:\n${e.message}"
                }
            }

            override fun onResponse(call: Call, response: Response) {
                // 在主线程更新UI
                runOnUiThread {
                    try {
                        val responseBody = response.body?.string() ?: "响应体为空"
                        tvResult.text = "GET请求成功:\n状态码: ${response.code}\n响应数据:\n$responseBody"
                    } catch (e: Exception) {
                        tvResult.text = "解析响应失败:\n${e.message}"
                    }
                }
            }
        })
    }

    /**
     * 发送POST请求
     */
    private fun sendPostRequest() {
        val url = etPostUrl.text.toString().trim()
        val jsonData = etPostData.text.toString().trim()

        // 检查输入是否为空
        if (url.isEmpty()) {
            Toast.makeText(this, "请输入POST请求URL", Toast.LENGTH_SHORT).show()
            return
        }

        if (jsonData.isEmpty()) {
            Toast.makeText(this, "请输入POST数据", Toast.LENGTH_SHORT).show()
            return
        }

        // 显示正在请求的提示
        tvResult.text = "正在发送POST请求...\nURL: $url\n数据: $jsonData"

        // 发送POST请求
        okHttpUtil.post(url, jsonData, object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                // 在主线程更新UI
                runOnUiThread {
                    tvResult.text = "POST请求失败:\n${e.message}"
                }
            }

            override fun onResponse(call: Call, response: Response) {
                // 在主线程更新UI
                runOnUiThread {
                    try {
                        val responseBody = response.body?.string() ?: "响应体为空"
                        tvResult.text = "POST请求成功:\n状态码: ${response.code}\n响应数据:\n$responseBody"
                    } catch (e: Exception) {
                        tvResult.text = "解析响应失败:\n${e.message}"
                    }
                }
            }
        })
    }
}